package com.bjpowernode.web.interceptor;

import com.bjpowernode.commons.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component // Spring自动扫描，并交给容器管理
public class AuthInterceptor implements HandlerInterceptor {

    // 方法上的注解要想被Spring解析，则类上必须有Spring的注解
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        // 跨域请求的预检（服务器是否允许跨域）操作
        if (method.equalsIgnoreCase("options")) {
            return true;
        }

        String token = request.getHeader("token");
        User user = (User) redisTemplate.opsForValue().get(token);

        if (StringUtils.isAnyBlank(user.getName(), user.getIdCard())) {

            Map respMap = new HashMap();
            respMap.put("success", false);
            respMap.put("message", "请先实名认证！");

            // 认证失败之后的操作
            respMap.put("op", "auth");

            String json = objectMapper.writeValueAsString(respMap);

            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(json);

            // 拦截请求
            return false;
        }

        // 放行
        return true;
    }
}
